<?php

namespace app\admin\controller\yxerp;

use app\common\controller\Backend;
use think\facade\Db;
use think\exception\ValidateException;

/**
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
 */
class Sku extends Backend
{
    protected object $model;
    protected string|array $preExcludeFields = ['id', 'create_time', 'update_time'];
    protected string|array $quickSearchField = ['sku_code'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\yxerp\Sku();
    }

    public function index(): void
    {
        // 构建查询条件
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        
        // 查询列表
        $list = $this->model
            ->withJoin(['product'], 'LEFT')
            ->where($where)
            ->order($order)
            ->paginate($limit);
            
        // 处理数据
        foreach ($list as &$row) {
            if ($row['attributes'] && is_string($row['attributes'])) {
                $row['attributes'] = json_decode($row['attributes'], true);
            }
        }
            
        $this->success('', [
            'list'   => $list,
            'total'  => $list->total(),
            'remark' => get_route_remark(),
        ]);
    }
    
    /**
     * 查看
     */
    public function view($id = null): void
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }
        
        // 处理attributes字段
        if ($row['attributes'] && is_string($row['attributes'])) {
            $row['attributes'] = json_decode($row['attributes'], true);
        }
        
        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            
            $data = $this->excludeFields($data);
            
            // 处理属性数据
            if (isset($data['attributes']) && is_array($data['attributes'])) {
                $data['attributes'] = json_encode($data['attributes']);
            } else if (isset($data['attributes']) && is_string($data['attributes']) && !empty($data['attributes'])) {
                // 尝试解析字符串属性为JSON
                try {
                    $attrs = json_decode($data['attributes'], true);
                    if (json_last_error() === JSON_ERROR_NONE) {
                        $data['attributes'] = json_encode($attrs);
                    }
                } catch (\Exception $e) {
                    // 解析失败，保持原样
                }
            }
            
            // 检查产品是否存在
            $product = \app\admin\model\yxerp\Product::find($data['product_id']);
            if (!$product) {
                $this->error(__('Product not found'));
            }
            
            // 检查SKU编码是否唯一
            $exists = $this->model->where('sku_code', $data['sku_code'])->find();
            if ($exists) {
                $this->error(__('SKU code already exists'));
            }
            
            // 开启事务
            Db::startTrans();
            try {
                // 验证
                if ($this->modelValidate) {
                    try {
                        $this->validate($data, 'app\admin\validate\yxerp\Sku');
                    } catch (ValidateException $e) {
                        $this->error($e->getMessage());
                    }
                }
                
                // 写入SKU数据
                $result = $this->model->save($data);
                if ($result === false) {
                    $this->error(__('Insert failed'));
                }
                
                // 提交事务
                Db::commit();
                $this->success(__('Added successfully'));
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        $this->success('');
    }
    
    /**
     * 编辑
     */
    public function edit($id = null): void
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            
            $data = $this->excludeFields($data);
            
            // 处理属性数据
            if (isset($data['attributes']) && is_array($data['attributes'])) {
                $data['attributes'] = json_encode($data['attributes']);
            } else if (isset($data['attributes']) && is_string($data['attributes']) && !empty($data['attributes'])) {
                // 尝试解析字符串属性为JSON
                try {
                    $attrs = json_decode($data['attributes'], true);
                    if (json_last_error() === JSON_ERROR_NONE) {
                        $data['attributes'] = json_encode($attrs);
                    }
                } catch (\Exception $e) {
                    // 解析失败，保持原样
                }
            }
            
            // 检查SKU编码是否唯一
            $exists = $this->model->where('sku_code', $data['sku_code'])->where('id', '<>', $id)->find();
            if ($exists) {
                $this->error(__('SKU code already exists'));
            }
            
            // 开启事务
            Db::startTrans();
            try {
                // 验证
                if ($this->modelValidate) {
                    try {
                        $this->validate($data, 'app\admin\validate\yxerp\Sku');
                    } catch (ValidateException $e) {
                        $this->error($e->getMessage());
                    }
                }
                
                // 更新SKU数据
                $result = $row->save($data);
                if ($result === false) {
                    $this->error(__('Update failed'));
                }
                
                // 提交事务
                Db::commit();
                $this->success(__('Update successful'));
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        // 解析属性字段
        if ($row['attributes'] && is_string($row['attributes'])) {
            $row['attributes'] = json_decode($row['attributes'], true);
        }
        
        $this->success('', [
            'row' => $row,
        ]);
    }
    
    /**
     * 删除
     */
    public function del($ids = ''): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }
        
        $pk = $this->model->getPk();
        $where = [[$pk, 'in', $ids]];
        
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($where)->select();
            $count = $list->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        $this->success(__('Deleted %s records', [$count]));
    }
}